using AutoMapper;
using BaseData.Domain;
using BaseData.WriteApi.Appcontext.Command.EweHistoryRecord_Files;
using MediatR;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;

namespace BaseData.WriteApi.Appcontext.CommandHandler.EweHistoryRecord_Files
{
    /// <summary>
    /// 创建种母历史记录命令处理器
    /// </summary>
    public class CreateEweHistoryRecordCommandHandler : IRequestHandler<CreateEweHistoryRecordCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<EweHistoryRecord> _eweHistoryRecordRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateEweHistoryRecordCommandHandler> _logger;

        public CreateEweHistoryRecordCommandHandler(
            IBaseRepository<EweHistoryRecord> eweHistoryRecordRepository,
            IMapper mapper,
            ILogger<CreateEweHistoryRecordCommandHandler> logger)
        {
            _eweHistoryRecordRepository = eweHistoryRecordRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理创建种母历史记录命令
        /// </summary>
        /// <param name="request">创建命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>创建结果</returns>
        public async Task<ApiResult<bool>> Handle(CreateEweHistoryRecordCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证请求参数
                if (request == null)
                {
                    _logger.LogWarning("创建种母历史记录请求参数为空");
                    return new ApiResult<bool> { Code = ApiEnum.新增失败, Message = "请求参数不能为空", data = false };
                }

                // 验证数据
                if (!request.Validate(out string errorMessage))
                {
                    _logger.LogWarning($"创建种母历史记录数据验证失败: {errorMessage}");
                    return new ApiResult<bool> { Code = ApiEnum.新增失败, Message = errorMessage, data = false };
                }

                // 创建实体
                var eweHistoryRecord = new EweHistoryRecord
                {
                    EweId = request.EweId,
                    MatingDate = request.MatingDate,
                    RamId = request.RamId,
                    PregnancyCheckDate = request.PregnancyCheckDate,
                    PregnancyResult = request.PregnancyResult,
                    DeliveryDate = request.DeliveryDate,
                    HealthyLambCount = request.HealthyLambCount,
                    HealthyLambTotalWeight = request.HealthyLambTotalWeight,
                    WeakLambCount = request.WeakLambCount,
                    DeformedCount = request.DeformedCount,
                    StillbirthCount = request.StillbirthCount,
                    MummyCount = request.MummyCount,
                    AbnormalCount = request.AbnormalCount,
                    CurrentParity = request.CurrentParity,
                    Note = request.Note,
                    IsDeleted = false,
                    Initialstate = false
                };

                // 保存到数据库
                var result = await _eweHistoryRecordRepository.AddAsync(eweHistoryRecord);
                
                if (result > 0)
                {
                    _logger.LogInformation($"成功创建种母历史记录，种母ID: {request.EweId}");
                    return new ApiResult<bool> { Code = ApiEnum.新增成功, Message = "种母历史记录创建成功", data = true };
                }
                else
                {
                    _logger.LogError($"创建种母历史记录失败，种母ID: {request.EweId}");
                    return new ApiResult<bool> { Code = ApiEnum.新增失败, Message = "种母历史记录创建失败", data = false };
                }
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.新增失败, Message = ex.Message, data = false };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"创建种母历史记录时发生系统异常: {ex.Message}");
                return new ApiResult<bool> { Code = ApiEnum.新增失败, Message = "系统异常，请联系管理员", data = false };
            }
        }
    }
}